﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.DeviceMsgQueues;
using HamcoWcs.Entitys.MesMsgQueues;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Service.Common;
using System;
using System.Threading;
using System.Xml;

namespace HamcoWcs.Service.Mes.Parsers
{
    /// <summary>
    /// 验证半成品入库栈板
    /// </summary>
    public class MesMsgParser_ValidatePalletInputRequest : MesMsgParserBase
    {
        public override void HandleEvent(MesMsgQueue message)
        {
            string code = XmlHelper.GetXPathText(message.Return, "//RETURNCODE");

            var machineNmae = XmlHelper.GetXPathText(message.Return, "//MACHINENAME");
            var portName = XmlHelper.GetXPathText(message.Return, "//PORTNAME");

            var pcon = _pconBaseService.GetPcon(machineNmae, portName);
            if (pcon == null)
            {
                message.Status = (int)EnumMesMsgStatus.Error;
                _logger.AddSystemErrorLog("MesMsgParser->ValidatePalletInputRequest:" + $"not found device [{machineNmae}_{portName}],TransactionId:{message.TransactionId}");
            }

            var pconSendMsg = new PconSendMsg()
            {
                PconName = (ushort)pcon.PconName,
            };


            if (code == "0")
            {
                // 码头验证入库信息成功:10
                pconSendMsg.Request = 10;
                // Mes要求延迟一秒发出退port信号
                Thread.Sleep(1000);
                pcon.PortState = "UR";
                _mesCommunicateService.PortTransferStateChanged(pcon);
            }
            else
            {
                // 码头验证入库信息失败:11 退回
                pconSendMsg.ErrorCode = 12;
                pconSendMsg.Request = 11;
            }

            InsertDeviceMsgInQueue(pcon, pconSendMsg);
            message.Status = (int)EnumMesMsgStatus.Closed;
        }

        private readonly IPconBaseService _pconBaseService;
        private readonly IMesCommunicateService _mesCommunicateService;
        public MesMsgParser_ValidatePalletInputRequest(ILoggerService loggerService, WcsDbContext wcsDbContext, IMapper mapper, IPconBaseService pconBaseService, IMesCommunicateService mesCommunicateService)
            : base(loggerService, wcsDbContext, mapper)
        {
            _pconBaseService = pconBaseService;
            _mesCommunicateService = mesCommunicateService;
        }

        public override string EventName => "VALIDATEPALLETINPUTREQUEST";
    }
}
